﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CustomeAuthentication.Models;

namespace CustomeAuthentication.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var viewModel = new LogonViewModel();
            return View(viewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(LogonViewModel viewModel)
        {
            if (Validate(viewModel.UserName, viewModel.Password))
            {
                var tkt = new FormsAuthenticationTicket(1, viewModel.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), viewModel.RememberMe, "your custom data");
                var cookiestr = FormsAuthentication.Encrypt(tkt);
                var ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                if (viewModel.RememberMe)
                    ck.Expires = tkt.Expiration;
                ck.Path = FormsAuthentication.FormsCookiePath;
                Response.Cookies.Add(ck);

                //string strRedirect;
                //strRedirect = Request["ReturnUrl"];
                //if (strRedirect == null)
                //    strRedirect = "default.aspx";
                //Response.Redirect(strRedirect, true);

                return RedirectToAction("UserInformation");
            }

            return View(viewModel);
        }

        [Authorize]
        public ActionResult UserInformation()
        {
            return View();
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        private bool Validate(string userName, string password)
        {
            return true;
        }

    }
}
